#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <pthread.h>
#include <unistd.h>
#include <libxml/SAX.h>
#include <string.h>
#include "config.h"
#include "dwmstatus_types.h"
#include "curl_sax.h"
#include "yweather.h"

String yweather_formated;

pthread_mutex_t yweather_exclusive = PTHREAD_MUTEX_INITIALIZER;

void set_yweather(char *my_weather) {
  pthread_mutex_lock(&yweather_exclusive);
  COPY(yweather_formated, my_weather, sizeof(yweather_formated));
  pthread_mutex_unlock(&yweather_exclusive);
}

void get_yweather(char *dest, size_t size) {
  pthread_mutex_lock(&yweather_exclusive);
  COPY(dest, yweather_formated, size);
  pthread_mutex_unlock(&yweather_exclusive);
}

void yweather_format_weather(YWeather *current) {

  String buffer;

  snprintf(buffer, sizeof(buffer), WEATHER_FORMAT, current->condition, current->temperature);
  set_yweather(buffer);
}

void yweather_update_weather() {
  xmlSAXHandler mySaxHandler;
  YWeather weather;

  memset(&weather, 0, sizeof(weather));
  yweather_set_sax_handler(&mySaxHandler);

  curl_sax_get_data(YAHOO_WEATHER_URL, &mySaxHandler, &weather);
  yweather_format_weather(&weather);
}

void *yweather_loop(void *ptr) {
  for (;;sleep(UPDATE_WEATHER_INTERVAL))
    yweather_update_weather();
}

void yweather_sax_on_start(void *ctx,
			   const xmlChar *localname,
			   const xmlChar *prefix,
			   const xmlChar *uri,
			   const int nb_namespaces,
			   const xmlChar **namespaces,
			   int nb_attributes,
			   int nb_defaulted,
			   const xmlChar **pattributes) {
  YWeather *weather = ctx;
#ifdef LOGGER
  printf("tag %s\n", localname);
#endif

  if (!strcmp(CURRENT_CONDITIONS_NODE, localname)) {
    curl_sax_get_attribute(YWEATHER_CONDITION_ATTRIBUTE, weather->condition, 500, nb_attributes, pattributes);
    curl_sax_get_attribute(YWEATHER_TEMP_ATTRIBUTE, weather->temperature, 500, nb_attributes, pattributes);
  }
}

void  yweather_set_sax_handler(xmlSAXHandler *sax_handler) {
    memset(sax_handler, 0, sizeof(xmlSAXHandler));
    sax_handler->initialized = XML_SAX2_MAGIC;
    sax_handler->startElementNs = yweather_sax_on_start;
}

void yweather_start() {
  pthread_t weather_thread;
  pthread_create(&weather_thread, NULL, yweather_loop, NULL);
}
